package com.web.base.user.provider;

import com.blue.core.dict.State;
import com.blue.jdbc.Page;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.user.exception.AddressException;
import com.web.base.user.facade.AddressFacade;
import com.web.base.user.message.AddressRequest;
import com.web.base.user.message.AddressResponse;
import com.web.base.user.model.Address;
import com.web.base.user.service.AddressService;
import com.web.base.user.util.AddressConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 收货地址接口实现类
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2018年06月26日
 */
@Component("userAddressProvider")
public class AddressProvider implements AddressFacade
{
	@Autowired
	private AddressService addressService;
	
	public AddressProvider()
	{
	}

	@Override
	public AddressResponse add(AddressRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Address address = AddressConvertor.toAddress(request);
		address = addressService.save(address);
		AddressResponse response = AddressConvertor.toResponse(address);
		return response;
	}

	@Override
	public AddressResponse update(AddressRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Address address = AddressConvertor.toAddress(request);
		address = addressService.save(address);
		AddressResponse response = AddressConvertor.toResponse(address);
		return response;
	}

	@Override
	public AddressResponse get(Integer id)
	{
		if (id == null)
			throw new AddressException("ID不能为空");
			
		Address address = addressService.get(id);
		AddressResponse response = AddressConvertor.toResponse(address);
		return response;
	}

	@Override
	public List<AddressResponse> listByUser(Integer userId, State state)
	{
		if (userId == null)
			throw new AddressException("用户ID不能为空");

		Address address = new Address();
		address.setUserId(userId);
		address.setState(state);
		List<Address> list = addressService.list(address);
		List<AddressResponse> responseList = AddressConvertor.toResponse(list);
		return responseList;
	}

	@Override
	public Page<AddressResponse> listPage(AddressRequest request, int start, int size)
	{
		Address address = AddressConvertor.toAddress(request);
		Page<Address> page = new Page<>(size);
		page.setCurPage(start);
		page = addressService.list(address, page);
		Page<AddressResponse> pageResponse = AddressConvertor.toResponse(page);
		return pageResponse;
	}
	
}
